package com.southsmart.sgeocserver.exception;


import cn.hutool.core.util.CharsetUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 *@author cjunxian
 *@date 2020/09/22  14:54:42
 *@doc 全局异常处理
 *@version 1.0.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public void handle(ApiException e,HttpServletResponse response) throws IOException {
        e.printStackTrace();
        String message = e.getMessage();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        if (e.getErrorCode() != null) {
            response.setStatus(e.getErrorCode().getCode());
            message = e.getErrorCode().getMessage();
        }
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(message);
        out.close();
    }

}
